let express = require('express');
let router = express.Router();
let moment =require("moment");
let utility = require("utility");
let loginDao  = require('../../model/admin/login.js')
let unililty = require('../../common/unility')
let backend_token = require('../../common/backend_token')

//渲染登录界面
router.get('/',async   function (req,res) {
    //生成登录界面token
    let tokenDate = moment().format('YYYY-MM-DD HH:mm:ss');
    let shaeVal = tokenDate +'web'+ parseInt(Math.random() * 99990 + 10, 10);
    let sha1Value = utility.sha1(shaeVal);
    await loginDao.insertToken(sha1Value,tokenDate); //token 存入数据库

    await res.render('login/login',{sha1Value:sha1Value})   
})


//登录验证
router.post('/', async  function(req,res){
    let userName = req.body.userName;
    let pwd = req.body.password;
    let loginToken =req.body.loginToken;
    if(!userName){
        return await res.json({status:203,msg:"用户名不能为空！"})
      }
      if(!pwd){
        return await res.json({status:203,msg:"密码不能为空！"})
      }
      if(!loginToken){
        return await res.json({status:400,msg:'非法请求,请从网页登录！'})
      }
      let validationToken  = await loginDao.validationToken(loginToken);
      if(validationToken.length==0){
        return await res.json({status:400,msg:'非法请求！'})
      }
      let validationUser  = await loginDao.validationUser(userName);  
      if(validationUser.length==0){
      return await res.json({status:203,msg:"用户名不存在，请重新输入！"}) 
     }
     let passwordMD5 = await unililty.encryptPWD(pwd);
     if(passwordMD5 !=validationUser[0].password){
      return await res.json({status:203,msg:"用户名或密码错误，请重新输入！"}) 
     }
     let api_token = await backend_token.createToken(userName,validationUser[0].id,validationUser[0].role);
     await loginDao.updateToken(validationUser[0].id,api_token);
     let  result={};
     result.api_token=api_token;
     result.userName=userName;
     result.role=validationUser[0].role;
     result.avatar=validationUser[0].avatar;
     result.userId =validationUser[0].id;
     req.session.user =result;
     await res.json({status:200,msg:"success"});
})

  //退出登录事件
  router.get('/logout',async function(req,res){
   delete  req.session.user ;  //清除登录session
  await res.redirect('/login')  
  })

   
module.exports = router;